<template>
    <div class="account-module">
      <div class="register" :style="{ background: 'url(' + bgImg + ') center  top', backgroundSize: '100% auto', 'min-height':'800px' }">
        <div class="header">
          <div class="left">
            <img class="min"  src="@/assets/logo_min.png" />
            <div class="title">全国青少年无人机大赛 | 用户管理中心</div>
          </div>
          <img class="logo" src="@/assets/r-logo.png" />
        </div>
        <div class="c" style="width: 1136px;">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="140px"
            class="ruleForm"
            :size="formSize"
            status-icon
          >
            <div class="regisetr-title">参赛代表队创建</div>
            <el-form-item label="参赛代表队名称">
              <div class="hint-input">
                <el-input v-model.trim="ruleForm.teamName" placeholder="请输入代表队名称"/>
                <div class="hint">如不填则默认与单位名相同</div>
              </div>
            </el-form-item>
            <!--
            <el-form-item label="登录账号">
             23678523727
            </el-form-item>
            -->
            <el-form-item label="参赛单位" prop="company">
              <div class="hint-input">
                <el-input v-model.trim="ruleForm.company" placeholder="请输入"/>
                <div class="hint">本信息将导入证件制作系统，一经填写不可修改，请务必填写准确！</div>
              </div>
            </el-form-item>
            <el-form-item label="所属地区" prop="province">
                <div class="hint-input">
                  <el-select style="width:220px" placeholder="省" v-model="ruleForm.province"  @change="selectCity">
                    <el-option
                        v-for="itemO in area.item"
                        :key="itemO.code"
                        :label="itemO.name"
                        :value="itemO.code">
                    </el-option>
                  </el-select>
                  &nbsp;
                  <el-select style="width:220px" placeholder="市" v-model="ruleForm.city" >
                    <el-option
                        v-for="itemO in areaCity.item"
                        :key="itemO.code"
                        :label="itemO.name"
                        :value="itemO.code">
                    </el-option>
                  </el-select>
                  <div class="hint">代表队只可参加本地区选拔赛，一经填写不可修改，请务必填写准确！</div>
                </div>
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="companyNo">
              <el-input v-model.trim="ruleForm.companyNo" placeholder="请输入统一社会信用代码"/>
            </el-form-item>

            <!--
            <el-form-item label="领队姓名" prop="leader">
              <div class="hint-input">
                <el-input v-model="ruleForm.leader" />
                <div class="hint">本信息将导入证件制作系统，请务必填写准确</div>
              </div>
            </el-form-item>
            <el-form-item label="联系方式(手机)" prop="phone">
              <el-input v-model="ruleForm.phone" placeholder="请输入"/>
              <span class="btn-code" @click="queryUser">查询</span>
            </el-form-item>
            <el-form-item label="领队性别" prop="sex">
              <el-radio-group v-model="ruleForm.sex">
                <el-radio label="1">男</el-radio>
                <el-radio label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="领队证件" prop="idType">
              <el-select v-model="ruleForm.idType" placeholder="请选择">
                <el-option label="身份证" value="1" />
                <el-option label="其他" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="idCard">
                <el-input v-model="ruleForm.idCard" placeholder="请输入"/>
            </el-form-item>
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="ruleForm.email" placeholder="请输入"/>
            </el-form-item>
            -->



            <el-form-item label="负责人授权书" prop="empower">
              <el-upload
                  class="avatar-uploader"
                  :action="baseUrl+'/front/upload'"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess3"
                  :before-upload="beforeAvatarUpload3"
              >
                <div class="image">
                  <img v-if="imageUrl3" :src="imageUrl3" class="img" />
                  <div v-else class="upload">
                    <img src="@/assets/common/upload.png">
                    <div class="text">上传负责人授权书</div>
                  </div>

                </div>
                <div class="hint">支持JPG/JPEG/PNG/PDF格式，不超过5MB<br/> <a target="_blank" style="text-decoration:underline; color: #00a0e9;" @click.stop="downLoad2()">下载</a></div>
              </el-upload>
            </el-form-item>


            <el-form-item>
              <div class="agreement"><el-checkbox v-model="ruleForm.checked2" /><span>*</span>点击同意并接受即表示您已阅读了解并同意 <el-button type="text" @click="dialogShow = true">《用户协议》</el-button></div>
               <div class="btns">
                  <el-button type="primary" @click="submitForm(ruleFormRef)">
                  创建
                  </el-button>
                  <el-button @click="resetForm(ruleFormRef)">取消</el-button>

                 <a href="javascript:void(0)" @click="skip()" style="margin-left: 20px; color: #959CA9; margin-top: 10px;">暂不创建，进入个人工作台</a>
               </div>
            </el-form-item>
          </el-form>
          <br/><br/><br/>
        </div>
      </div>
    </div>

  <el-dialog title="用户协议" v-model="dialogShow" width="700px">
    <div style="text-align: left; line-height: 35px;" class="student">
      一、参赛选手：<br/>
      1.本人自愿报名参加全国青少年无人机大赛。<br/>
      2.本人填报的信息均真实有效。<br/>
      3.本人在正式提交参赛前，已检查核实所有填报信息和上传文件，确认符合申报要求和赛项规定，如因填写错误造成的后果由本人自行承担。<br/>
      二、大赛组委会<br/>
      对收集的“全国青少年无人机大赛”的参赛选手信息仅限于本大赛组织管理使用。<br/>
      <br/><br/>
    </div>
    <div style="text-align: center" slot="footer" class="dialog-footer">
      <el-button @click="dialogShow = false">我知道了</el-button>
    </div>
  </el-dialog>

  </template>
<script lang="ts" setup>
import app from "@/constants/app";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";

import type { UploadProps } from 'element-plus'
import { useRouter } from "vue-router";
import baseService from "@/service/baseService";
import {ElMessage} from "element-plus";
let router = useRouter();
const bgImg = require('../../assets/bg.png')
const imageUrl = ref('')
const imageUrl2 = ref('')
const imageUrl3 = ref('')
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const baseUrl = app.api;
const ruleForm = reactive({
  email: "",
  teamName: "",
  company: "",
  companyNo: '',
  province: '',
  city: '',
  leader: "",
  sex: "",
  idType: "",
  idCard: "",
  phone: "",
  header: "",
  empower: "",
  empower2: "",
  code: "",
  leaderId: null,
  checked2: true
});
const dialogShow = ref(false);
const area = reactive({
  code:'0',
  item:[]
});
const areaCity = reactive({
  code: '0', item: []
});

const rules = reactive<FormRules>({
  email: [{required: true, message: "请输入邮箱", trigger: "blur"}],
  teamName: [{required: true, message: "请输入代表队名称", trigger: "blur"}],
  company: [{required: true, message: "请输入参赛单位", trigger: "blur"}],
  province: [{required: true, message: "请选择省", trigger: "change"}],
  companyNo: [{required: true, message: "请输入组织机构代码", trigger: "blur"}],
  leader: [{required: true, message: "请输入领队姓名", trigger: "blur"}],
  sex: [{required: true, message: "请选择性别", trigger: "change"}],
  idType: [{required: true, message: "请选择证件", trigger: "change",}],
  idCard: [{required: true, message: "请输入证件号码", trigger: "blur"}],
  phone: [{required: true, message: "请输入手机号", trigger: "blur"}],
  code: [{required: true, message: "请输入验证码", trigger: "blur"}],
  empower: [{required: true, message: "请上传负责人授权书", trigger: "blur"}],
});

const getAraeList = async (target: any) => {
  baseService.get("/front/fast/sys/areaDict/list?pid="+target.code).then((e:any)=>{
    target.item=e.data;
  });
};
const selectCity = async () => {
  if (ruleForm.province) {
    areaCity.code = ruleForm.province;
    getAraeList(areaCity);
  } else {
    areaCity.item = [];
  }
};

getAraeList(area);


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!ruleForm.checked2) {
    ElMessage.error("您未同意用户协议，请先同意！");
    return;
  }
  if (!formEl) return;

 /* if(!ruleForm.empower){
    ElMessage.error("请上传领队授权书！");
    return;
  }*/
  // 校验市必须选择
  if (!ruleForm.city) {
    ElMessage.error("请选择市！");
    return;
  }

  if(!ruleForm.empower){
    ElMessage.error("请上传负责人授权书！");
    return;
  }

  await formEl.validate((valid, fields) => {
    if (valid) {
      baseService
          .post("/front/spteam/save", ruleForm)
          .then((res) => {
                if (res.code === 0) {
                  ElMessage.success("提交成功！");
                  //延迟1s执行
                  setTimeout(() => {
                    // 跳转到登录页面
                    router.push("/");
                  }, 1000);
                } else {
                  ElMessage.error(res.msg);
                }
              }
          );

    } else {

    }
  });
};

/**
 * 查询用户信息
 * @param formEl
 */
const queryUser = async (formEl: FormInstance | undefined) => {
  //姓名不能为空
  if (ruleForm.leader === "") {
    ElMessage.error("姓名不能为空！");
    return;
  }
  //校验手机号不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号不能为空！");
    return;
  }
  baseService
      .post("/front/spuser/queryUser", {
        realName: ruleForm.leader,
        phone: ruleForm.phone,
        roleId: 1
      })
      .then((res) => {
            if (res.code === 0) {
              ruleForm.idType = res.data.idType;
              ruleForm.idCard = res.data.idCard;
              ruleForm.sex  = res.data.sex+'';
              ruleForm.email = res.data.email;
              ruleForm.header = res.data.header;
              ruleForm.leaderId = res.data.id;
              imageUrl.value = res.data.header;
            } else {
              ElMessage.error(res.msg);
            }
          }
      );
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    router.push("/");
};


const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg' || rawFile.type == 'application/pdf')) {
    ElMessage.error('仅支持JPG/JPEG/PNG/PDF格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
      ElMessage.error('授权书不能超过5MB!')
        return false
    }
    return true
}

const handleAvatarSuccess2: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.empower = response.data.src;
  imageUrl2.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg' || rawFile.type == 'application/pdf')) {
    ElMessage.error('仅支持JPG/JPEG/PNG/PDF格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('一寸证件照不能超过2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess3: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.empower = response.data.src;
  imageUrl3.value = URL.createObjectURL(uploadFile.raw!)
  if(response.data.showSrc){
    imageUrl3.value = response.data.showSrc;
  }
}

const beforeAvatarUpload3: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile.type);
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg' || rawFile.type == 'application/pdf')) {
    ElMessage.error('仅支持JPG/JPEG/PNG/PDF格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('授权书不能超过5MB!')
    return false
  }
  return true
}

const downLoad1 = async () => {
  let a = document.createElement('a');
  let evt = document.createEvent('MouseEvents');
  a.download = '领队授权书';
  a.href = '/doc/全国青少年无人机大赛-领队授权书.docx';
  evt.initEvent('click',true,true);
  a.dispatchEvent(evt);
  window.URL.revokeObjectURL(a.href);
}

const downLoad2 = async () => {
  let a = document.createElement('a');
  let evt = document.createEvent('MouseEvents');
  a.download = '代表队负责人授权书';
  a.href = '/doc/全国青少年无人机大赛-代表队负责人授权书.docx';
  evt.initEvent('click',true,true);
  a.dispatchEvent(evt);
  window.URL.revokeObjectURL(a.href);
}

//跳过创建
const skip = async () => {
  router.push('/info/');
}

</script>
<style lang="scss" scoped>
@import "account.scss";
</style>
<style lang="scss">
.ruleForm {
    .el-form-item--default .el-form-item__label {
        font-weight: $font-weight-bold;
    }
}
</style>
